package com.by.service.impl;

import com.by.bean.Employee;
import com.by.bean.User;
import com.by.common.crud.BaseServiceImpl;
import com.by.common.ex.BusinessException;
import com.by.common.utils.Assert;
import com.by.mapper.EmployeeMapper;
import com.by.mapper.UserMapper;
import com.by.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;

@Service
public class EmployeeServiceImpl extends BaseServiceImpl<Employee, EmployeeMapper> implements EmployeeService {

    @Autowired
    UserMapper userMapper;

    /**
     * 如果方法中出现异常  事务会回滚
     *
     * @param entity 要保存的对象
     * @return
     */
    @Transactional  //事务管理
    @Override
    public int save(Employee entity) {
        //设置员工角色为销售人员
        entity.setRoleId(5);
        entity.getUser().setRoleId(5);
        //保存用户  1为公司员工
        entity.getUser().setType(1);
        //保存用户
        int rs = userMapper.save(entity.getUser());
        Assert.isNotSuccess(rs, "用户保存失败");
        //用户保存成功 查询用户的id 保存到员工表
        User user = userMapper.queryByAccount(entity.getUser().getUsername());
        entity.setUserId(user.getId());
        //保存员工
        return super.save(entity);
    }

    /**
     * 修改员工表
     *
     * @param entity
     * @return
     */
    @Transactional  //事务管理
    @Override
    public int update(Employee entity) {

        int res = super.update(entity);
        Assert.isNotSuccess(res, "修改失败");
        int update = userMapper.update(entity.getUser());
        Assert.isNotSuccess(update, "用户修改失败");
        return 1;
    }

    @Transactional
    @Override
    public int delete(Serializable id) {
        int res = super.delete(id);
        Assert.isNotSuccess(res, "删除员工失败");
        //根据用户id查询userId
        int userId = baseMapper.queryUserId(id);
        int del = userMapper.delete(userId);
        Assert.isNotSuccess(del, "删除用户失败");
        return 1;
    }

    @Override
    public int queryUserId(int id) {
        return baseMapper.queryUserId(id);
    }
}
